package com.example.fantacylib

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.example.baseutils.activity.BaseLoadActivity
import com.example.baseutils.showToast
import com.example.baseutils.start
import com.example.fantacylib.databinding.ActivityFantacyMainBinding
import com.example.fantacylib.ui.BannerImage
import com.example.fantacylib.ui.ImageAdapter
import com.example.net.http.FantacyRetrofitCreator
import com.example.printlib.PrintEngine
import com.example.printlib.PrintService
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch


class FantacyMain : BaseLoadActivity() {
    private val TAG = "FantacyMain"
    private lateinit var binding: ActivityFantacyMainBinding

    private val bannerList = mutableListOf<BannerImage>()

    private val mainScope = CoroutineScope(Dispatchers.Main)

    private var price: String? = null
    private var countTime: Int = 15
    private lateinit var bannerAdapter: ImageAdapter

    companion object {
        var spuId = 0
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_fantacy_main)
        banner()
        binding.btnShout.setOnClickListener {
            if (price == null) {
                "数据未获取到，请联网后再重试".showToast(this@FantacyMain)
                return@setOnClickListener
            }
            CaptureActivity().start(this) {
                putExtra(CaptureActivity.COUNT_TIME, countTime)
                putExtra(CaptureActivity.PRICE_KEY, price)
            }
        }
        binding.tvWordMain.setOnLongClickListener {
            DeviceActivity().start(this@FantacyMain)
            true
        }
        PrintEngine.getInstance().initEngine(this) {
            PrintEngine.getInstance().addPrintCallback { state, description ->
                if (binding.tvPrint.visibility == View.GONE && (state == PrintService.PrintServerStatus.disconnected || state == PrintService.PrintServerStatus.error)) {
                    "连接打印机失败".showToast(this@FantacyMain)
                    binding.tvPrint.visibility = View.VISIBLE
                    return@addPrintCallback
                }
                if (binding.tvPrint.visibility == View.VISIBLE && (state != PrintService.PrintServerStatus.disconnected)) {
                    "连接成功".showToast(this@FantacyMain)
                    binding.tvPrint.visibility = View.GONE
                }

            }
        }

        lifecycleScope.launch(Dispatchers.IO) {
            while (this.isActive) {
                if(!isActive)
                    break
                FantacyRetrofitCreator.pushHeart()
                delay(10 * 1000)
            }
        }
    }

    override fun onLoad() {
        mainScope.launch {
            val device = FantacyRetrofitCreator.getDeviceInfo() ?: return@launch
            spuId = device.spuId
            val bannerResult = FantacyRetrofitCreator.getBanner(spuId) ?: return@launch
            price = bannerResult.price
            countTime = device.countdown ?: 15
            bannerList.clear()
            bannerResult.sliderPicUrls.forEach {
                bannerList.add(BannerImage(it))
            }
            delay(1000)
            bannerAdapter.updateData(bannerList)
            "获取数据成功".showToast(this@FantacyMain)
        }
    }

    private fun banner() {
        for (i in 0..2) {
            bannerList.add(BannerImage("https://img.js.design/assets/img/66c2c1a1bed65308b201d100.jpg"))
        }
        bannerAdapter = ImageAdapter(bannerList)
        binding.bannerMain.addBannerLifecycleObserver(this)
            .setAdapter(bannerAdapter)
            .setIndicator(CircleIndicator(this))

        binding.bannerMain.setOnBannerListener { data, position ->
            Log.i(TAG, "onBannerClick: $data position:$position")

        }
        binding.bannerMain.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                Log.i(TAG, "onPageSelected: $position")
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()
        PrintEngine.getInstance().unit(this)
    }
}